package com.example.xgakj.newterminal.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import com.example.xgakj.mylibrary.mvp.utils.TimeUtil;
import com.example.xgakj.newterminal.base.Parameters;

import java.nio.ByteBuffer;

/**
 * @author Administrator
 * @date 2017-10-28
 */

public class CaptureSreenUtil {
    MediaProjectionManager mMediaProjectionManager;
    MediaProjection mMediaProjection;
    public int mResultCode;
    public Intent mResultData;
    VirtualDisplay mVirtualDisplay;
    private int mScreenDensity;
    private int mWindowWidth;
    private int mWindowHeight;
    private WindowManager mWindowManager;
    private ImageReader mImageReader;
    public static final int REQUEST_MEDIA_PROJECTION = 1;
    private Bitmap mBitmap;
    private ImageReader mImageReader2;
    private Activity mActivity;

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void createEnvironment(Activity activity) {
        mActivity=activity;
        mWindowManager = (WindowManager)activity. getSystemService(Context.WINDOW_SERVICE);
        mWindowWidth = getScreenWidth();
        mWindowHeight = getScreenHeight();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        mWindowManager.getDefaultDisplay().getMetrics(displayMetrics);
        mScreenDensity = displayMetrics.densityDpi;
        /**
         * mImageReader是截取竖屏。mImageReader2截取横屏
         */
        if (mWindowHeight>mWindowWidth){
            mImageReader = ImageReader.newInstance(mWindowWidth, mWindowHeight, 0x1, 1);
            mImageReader2 = ImageReader.newInstance(mWindowHeight, mWindowWidth, 0x1, 2);
        }else {
            mImageReader = ImageReader.newInstance(mWindowHeight, mWindowWidth, 0x1, 1);
            mImageReader2 = ImageReader.newInstance(mWindowWidth, mWindowHeight, 0x1, 2);
        }



        mMediaProjectionManager = (MediaProjectionManager)
                activity.getSystemService(Context.MEDIA_PROJECTION_SERVICE);

//        mVideoPath = Environment.getExternalStorageDirectory().getPath() + "/crosswalk/record/";
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void setmResultData(int resultCode, Intent resultData){
        mResultCode=resultCode;
        mResultData=resultData;
        setUpMediaProjection();
        setUpVirtualDisplay();
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void startCapture() throws Exception {
        Image image = getReader().acquireLatestImage();
        if (image == null) {
            return;
        }
        int width = image.getWidth();
        int height = image.getHeight();
        final Image.Plane[] planes = image.getPlanes();
        final ByteBuffer buffer = planes[0].getBuffer();
        int pixelStride = planes[0].getPixelStride();
        int rowStride = planes[0].getRowStride();
        int rowPadding = rowStride - pixelStride * width;
        mBitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
        mBitmap.copyPixelsFromBuffer(buffer);
        mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, width, height);
        image.close();
        stopScreenCapture();
        if (mBitmap != null) {

            FileUtil.savePictureToFile(mBitmap, Parameters.SCREEN_SHOTS, TimeUtil.getCurrDateTime()+".png");
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void stopScreenCapture() {
        if (mVirtualDisplay != null) {
            mVirtualDisplay.release();
            mVirtualDisplay = null;
        }
    }



    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public boolean startScreenCapture() {
        Log.e("0525", "startScreenCapture");
        if (this == null) {
            return false;
        }
        if (mMediaProjection != null) {
            Log.e("0525", "startScreenCapture 1");
            setUpVirtualDisplay();
            return true;
        } else if (mResultCode != 0 && mResultData != null) {
            Log.e("0525", "startScreenCapture 2");
            setUpMediaProjection();
            setUpVirtualDisplay();
            return true;
        } else {
            Log.e("0525", "startScreenCapture 3");
            // This initiates a prompt dialog for the user to confirm screen projection.
            mActivity.startActivityForResult(
                    mMediaProjectionManager.createScreenCaptureIntent(),
                    REQUEST_MEDIA_PROJECTION);
            return false;
        }
    }



    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void setUpMediaProjection() {
        mMediaProjection = mMediaProjectionManager.getMediaProjection(mResultCode, mResultData);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void setUpVirtualDisplay() {

        mVirtualDisplay = mMediaProjection.createVirtualDisplay("ScreenCapture",
                getScreenWidth(), getScreenHeight(), mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                getReader().getSurface(), null, null);
    }
    private ImageReader getReader() {
        return isLandscape() ? mImageReader2 : mImageReader;

    }
    public boolean isLandscape() {
        Configuration mConfiguration = mActivity.getResources().getConfiguration(); // 获取设置的配置信息
        int ori = mConfiguration.orientation; // 获取屏幕方向

        if (ori == Configuration.ORIENTATION_LANDSCAPE) {

            // 横屏
            return true;
        } else if (ori == Configuration.ORIENTATION_PORTRAIT) {

            // 竖屏
            return false;
        }
        return false;
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void release(){
        if (mMediaProjection!=null){
            mMediaProjection.stop();
            mMediaProjection=null;
        }
        if (mVirtualDisplay!=null){
            mVirtualDisplay.release();
            mVirtualDisplay=null;
        }
    }

    /**
     * 获得屏幕宽高
     */
    private int getScreenWidth() {
        int width = mWindowManager.getDefaultDisplay().getWidth();
        return width;
    }

    /**
     * 获得屏幕宽高
     */
    private int getScreenHeight() {

        int height = mWindowManager.getDefaultDisplay().getHeight();
        return height;
    }

    /**
     * 获得DPI
     */

    private int getScreenDpi() {
        DisplayMetrics metrics = new DisplayMetrics();
        mWindowManager.getDefaultDisplay().getMetrics(metrics);
        return metrics.densityDpi;
    }


}
